<!--
 * @Author: wangming
 * @Date: 2021-06-15 16:24:40
 * @LastEditors: wangming
 * @LastEditTime: 2022-04-26 18:24:04
 * @Description: file content
-->
<template>
  <el-select
    :multiple="config.type !== 'RELATION_REFERENCE'"
    :value="values"
    filterable
    remote
    clearable
    @change="change"
    :remote-method="remoteRethod"
  >
    <el-option
      v-for="item in optionsList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
    </el-option>
    <div v-if="optionsList.length > 29" class="g9 f12 pl20 pr20">
      只显示前30条结果，请完善搜索关键字
    </div>
  </el-select>
</template>

<script>
import { getHmdictionaryOptions } from "@/apis/paas/HmDictionaryController.js";
import { postHmhttprequestdefinitionExecute } from "@/apis/paas/HmHttpRequestDefinitionController.js";
export default {
  props: ["value", "config"],
  data() {
    return {
      optionsList: [],
    };
  },
  created() {
    this.getApiOptions();
  },
  watch: {
    "config.code": function () {
      this.getApiOptions();
    },
  },
  computed: {
    values() {
      if (this.config.type === "RELATION_REFERENCE") {
        return this.value;
      } else {
        let list = this.value?.match(/\w+/g) || [];
        return list.map((id) => `[${id}]`);
      }
    },
  },
  methods: {
    change(id) {
      if (this.config.type === "RELATION_REFERENCE") {
        this.$emit("input", id);
      } else {
        this.$emit("input", id?.join("") || undefined);
      }
    },
    async remoteRethod(param) {
      this.getApiOptions(param);
    },
    async getApiOptions(keyword = "") {
      let O = {
        limit: 30,
      };
      if (!!keyword) {
        O.keyword = keyword;
      }
      let { modelCode, relationType, code: fieldCode, config } = this.config;
      if (!relationType) return;
      let data = [];
      if (relationType === "DICTIONARY") {
        let values = JSON.parse(config);
        data = await getHmdictionaryOptions(
          { type: values.value },
          { useCache: true }
        );
        data = data.map(({ optionValue, optionName }) => ({
          label: optionName,
          id: optionValue,
        }));
      } else {
        data = await postHmhttprequestdefinitionExecute({
          key: "selectList",
          modelKey: modelCode,
          values: {
            _RELATION_TYPE_: relationType,
            fieldCode,
            ...O,
            _IDS_: this.value?.match(/\w+/g)?.join(",") || "",
          },
        });
      }

      this.optionsList = data.map(({ id, label }) => {
        return {
          value: this.config.type === "RELATION_REFERENCE" ? id : `[${id}]`,
          label,
        };
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
